package com.qyhl.webtv.module_news.news.smallvideo.fragment;

import android.Manifest;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.ViewPageFragment;
import com.qyhl.webtv.commonlib.utils.view.video.smallvideo.QYSVideoPlayer;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/6.
 */

public class SmallVideoFragment extends ViewPageFragment implements SmallVideoFragmentContract.SVFragmentView {
    public final static String TAG = "SV";
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @BindView(R2.id.activity_list_video)
    RelativeLayout activityListVideo;

    private String sectionId;

    private int page = 1;

    private List<NewsBean> mDataList;

    private SmallVideoFragmentPresenter mPresenter;


    private CommonAdapter<NewsBean> commonAdapter;


    public SmallVideoFragment() {

    }

    public static SmallVideoFragment newInstance(String sectionId) {
        SmallVideoFragment fragment = new SmallVideoFragment();
        fragment.setSectionId(sectionId);
        return fragment;
    }

    private void setSectionId(String newId) {
        this.sectionId = newId;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.news_fragment_smallvideo, container, false);
            ButterKnife.bind(this, rootView);
        }
        initView();
        setListener();
        return rootView;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SmallVideoFragmentPresenter(this);

        mDataList = new ArrayList<>();

        //设置刷新头
        refresh.setEnableLoadMore(true);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);


        recyclerView.setAdapter(commonAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.news_item_small_video, mDataList) {
            @Override
            protected void convert(ViewHolder viewHolder, final NewsBean item, final int position) {
                //分享
                TextView shareBtn = viewHolder.getView(R.id.item_share);
                shareBtn.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(getActivity(), 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        MShareBoard shareBoard = new MShareBoard(getActivity(), item.getID(), item.getTitle(), item.getLogo(), "", 4, true);
                        shareBoard.showPopupWindow();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(getContext());
                    }
                }));

                TextView comment = viewHolder.getView(R.id.item_comment);
                if (StringUtils.isNotEmpty(item.getComment()) && !"0".equals(item.getComment())) {
                    comment.setText(item.getComment());
                } else {
                    comment.setText("评论");
                }
                comment.setOnClickListener(v -> {

                    Bundle bundle = new Bundle();
                    bundle.putString("newsId", item.getID());
                    RouterManager.router(ARouterPathConstant.SMALL_VIDEO_DETAIL_ACTIVITY,bundle);

                });

                final QYSVideoPlayer videoPlayer = viewHolder.getView(R.id.video_player);
                //设置封面
                ImageView imageView = new ImageView(getContext());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                Glide.with(getContext())
                        .load(item.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_video_default).error(R.drawable.cover_video_default).centerCrop())
                        .into(imageView);
                videoPlayer.setThumbImageView(imageView);
                videoPlayer.setRotateViewAuto(false);
                videoPlayer.setLockLand(true);
                videoPlayer.setPlayTime(mDataList.get(position).getDuration());
                videoPlayer.setUp(item.getLink(), true, item.getTitle());
                videoPlayer.setPlayNum(item.getClickCount());

                if (videoPlayer.isIfCurrentIsFullscreen()) {
                    videoPlayer.getBackButton().setVisibility(View.VISIBLE);
                } else {
                    videoPlayer.getBackButton().setVisibility(View.GONE);
                }

                videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        videoPlayer.startWindowFullscreen(getContext(), true, true);
                    }
                });

                //设置标签
                TextView tagOne = viewHolder.getView(R.id.tag_one);
                TextView tagTwo = viewHolder.getView(R.id.tag_two);
                TextView tagThree = viewHolder.getView(R.id.tag_three);
                tagOne.setVisibility(View.GONE);
                tagTwo.setVisibility(View.GONE);
                tagThree.setVisibility(View.GONE);

                List<NewsBean.Tag> tagList = item.getTags();
                int index;
                if (tagList != null && tagList.size() > 0) {
                    if (tagList.size() > 3) {
                        index = 3;
                    } else {
                        index = tagList.size();
                    }
                    for (int i = 0; i < index; i++) {
                        String name = tagList.get(i).getTagName();
                        switch (i) {
                            case 0:
                                tagOne.setText(name);
                                tagOne.setVisibility(View.VISIBLE);
                                break;
                            case 1:
                                tagTwo.setText(name);
                                tagTwo.setVisibility(View.VISIBLE);
                                break;
                            case 2:
                                if (tagTwo.getWidth() != 0) {
                                    checkVisibility(tagTwo, tagThree, name);
                                } else {
                                    measuredThree(tagTwo, tagThree, name);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                } else {
                    tagOne.setVisibility(View.GONE);
                    tagTwo.setVisibility(View.GONE);
                    tagThree.setVisibility(View.GONE);
                }
            }
        });
        mPresenter.getDatas(sectionId, page + "");
    }

    private void measuredThree(final TextView tagTwo, final TextView tagThree, final String name) {
        ViewTreeObserver viewTreeObserver = tagTwo.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tagTwo.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                checkVisibility(tagTwo, tagThree, name);
            }
        });
    }

    private void checkVisibility(TextView tagTwo, TextView tagThree, String name) {
        LinearLayout parent = (LinearLayout) tagTwo.getParent();
        //剩余距离
        int dis = parent.getWidth() - tagTwo.getRight() - StringUtils.dip2px(getContext(), 18);
        //判断剩余距离
        if (dis >= tagThree.getPaint().measureText(name)) {
            tagThree.setText(name);
            tagThree.setVisibility(View.VISIBLE);
        }
    }



    /**
     * 设置监听
     */
    private void setListener() {
        //重载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getDatas(sectionId, page + "");
            }
        });

        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getDatas(sectionId, page + "");
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getDatas(sectionId, page + "");
            }
        });

    }

    /**
     * 设置数据
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setDatas(List<NewsBean> beanList, boolean isMore) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        page++;

        if (isMore) {
            mDataList.addAll(beanList);
        } else {
            mDataList.clear();
            mDataList.addAll(beanList);
        }

        commonAdapter.notifyDataSetChanged();
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * toast
     *
     * @param msg
     */
    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Toasty.normal(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 日志
     *
     * @param msg
     */
    @Override
    public void showLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    public boolean onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(getActivity())) {
            return true;
        }
        return false;
    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (!isVisible) {
            GSYVideoManager.onPause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

}
